﻿using System;
using System.IO.IsolatedStorage;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.WindowsAzure.MobileServices;
using SkiTracker.Model;

namespace SkiTracker.ViewModel
{
    public class MainViewModel : ViewModelBase 
    {

        private readonly IMobileServiceTable<Device> _deviceTable = App.MobileService.GetTable<Device>();

        public MainViewModel()
        {
            SaveCommand = new RelayCommand(InsertOrUpdateDeviceDataAsync, () => IsInitialized); 

            NavigateToCommand = new RelayCommand<string>(page => App.RootFrame.Navigate(new Uri(string.Format(@"/View/{0}Page.xaml", page), UriKind.Relative)), 
                                                         page => IsDeviceRegisterd);

            UpdateUi();

            App.CurrentApp.DeviceLoaded += (sender, args) => UpdateUi();

        }

        private void UpdateUi()
        {
            RaisePropertyChanged(() => Device);
            RaisePropertyChanged(() => IsInitialized);
            IsDeviceRegisterdChanged();
            SaveCommand.RaiseCanExecuteChanged();
        }

        private async void InsertOrUpdateDeviceDataAsync()
        {
            Device.Color = App.CurrentApp.AccentColor;

            if (!IsDeviceRegisterd)
            {
                // insert

                try
                {
                    await _deviceTable.InsertAsync(Device);

                    IsolatedStorageSettings.ApplicationSettings.Add("Id", Device.Id);
                    IsolatedStorageSettings.ApplicationSettings.Save();

                }
                catch
                {
                    Device.Id = 999;
                }
            }
            else
            {
                // update

                await _deviceTable.UpdateAsync(Device);
            }

            RaisePropertyChanged(() => Device);
            IsDeviceRegisterdChanged();

        }

        public Device Device
        {
            get { return App.CurrentApp.CurrentDevice; }
        }

        private void IsDeviceRegisterdChanged()
        {
            RaisePropertyChanged(() => IsDeviceRegisterd);
            NavigateToCommand.RaiseCanExecuteChanged();
        }
        public bool IsInitialized
        {
            get { return Device != null; }
        }
        public bool IsDeviceRegisterd
        {
            get
            {
                return Device != null && Device.Id > 0;
            }
        }

        public RelayCommand SaveCommand { get; private set; }
        public RelayCommand<string> NavigateToCommand { get; private set; }

    }
}
